package cloud

import (
	"dgo/goutils/utils"
	"dgo/plg/plgnet"
	"fmt"
	"gitee.com/ymofen/supervalue"
	"io/ioutil"
	"net/http"
	"net/url"
)

/*
参数：
rescode:wx.login获取的code(必传);

返回值：
openid:用户openid
*/
func (this *PlgVxApiXcx) onHttpLoginGetOpenid(w http.ResponseWriter, r *http.Request) {

	req := plgnet.NewPlgHttpRec(w, r)
	//req := PrjHttpUtils.NewHttpRec(w,r)

	req.CheckDecodeBody()

	//data4 := req.QryAsString("data", "")

	rescode := req.QryAsString("rescode", "")

	if len(rescode) < 1 {
		req.Resp.SetKeyValues("code", -1, "msg", "未获取到rescode!")
		req.ResponseAsJSON()
		return
	}

	resp, err4 := http.PostForm("https://api.weixin.qq.com/sns/jscode2session",
		url.Values{"appid": {this.appid}, "secret": {this.appsecret}, "js_code": {rescode}, "grant_type": {"authorization_code"}})

	//time.Sleep(time.Duration(1000)*time.Millisecond)
	if err4 != nil {
		// handle error
		utils.Log.Warn("微信官方接口调用出现问题：", err4)
		req.Resp.SetKeyValues("code", -1, "msg", "微信官方接口调用出现问题!")
		req.ResponseAsJSON()
		return
	}

	defer resp.Body.Close()
	body, err5 := ioutil.ReadAll(resp.Body)
	if err5 != nil {
		// handle error
		utils.Log.Warn("微信官方接口调用后ReadAll函数出现问题：", err5)
		req.Resp.SetKeyValues("code", -1, "msg", "微信官方接口调用后ReadAll函数出现问题!")
		req.ResponseAsJSON()
		return
	}
	//fmt.Println(body)
	jsons := wrapper.NewSVObjectFromBufIfErrThenNew(body)

	openid := jsons.StringByName("openid", "")
	req.Resp.SetKeyValues("code", 0, "openid", openid)
	req.ResponseAsJSON()
	return
	//fmt.Println(jsons)
	//allneedmsg.session_key = jsons.StringByName("session_key", "")
	//allmsgJson, _ := wrapper.NewSVFromBuf([]byte(allneedmsg.allmsg))
}

/*
code:wx.login获取的code(必传);
phonenumbermsg:微信bindgetphonenumber绑定的函数的实参e(必传);
userinfo:wx.getUserInfo执行成功后返回的res里的userInfo字段,主要作用于获取用户昵称和头像地址(非必传);

返回值：
包含phoneNumber（手机号）、nickName（微信昵称）、avatarUrl（头像地址）的json
*/
func (this *PlgVxApiXcx) onHttpGetPhoneNumber(w http.ResponseWriter, r *http.Request) {

	req := plgnet.NewPlgHttpRec(w, r)
	//req := PrjHttpUtils.NewHttpRec(w,r)

	req.CheckDecodeBody()

	//data4 := req.QryAsString("data", "")

	code := req.QryAsString("rescode", "")
	userinfo := req.QryAsString("userinfo", "")
	phonenumbermsg := req.QryAsString("phonenumbermsg", "")

	phonejson, errp := this.WxGetuserPhonenumber(code, phonenumbermsg, userinfo)
	if phonejson == nil {
		fmt.Println(errp)
		utils.Log.Warn(errp)
		req.Resp.SetKeyValues("code", -1, "msg", errp)
		req.ResponseAsJSON()
		return
	} else {
		req.Resp.SetKeyValues("code", 0, "allneedmsg", phonejson)
		req.ResponseAsJSON()
		return
	}
}

func NewPayObject(appid string, appsecret string) *PlgVxApiXcx {
	obj := &PlgVxApiXcx{appid: appid, appsecret: appsecret}
	return obj
}

/*
code:wx.login获取的code(必传);
phonenumbermsg:微信bindgetphonenumber绑定的函数的实参e(必传);
userinfo:wx.getUserInfo执行成功后返回的res里的userInfo字段,主要作用于获取用户昵称和头像地址(非必传);

返回值：
包含phoneNumber（手机号）、nickName（微信昵称）、avatarUrl（头像地址）的json
*/
func (this *PlgVxApiXcx) WxGetuserPhonenumber(code string, phonenumbermsg string, userinfo string) (*wrapper.SuperValue, string) {

	//记录最后报错的信息
	if utils.GoFunCatchException {
		defer utils.PanicHandler()
	}

	resp, err4 := http.PostForm("https://api.weixin.qq.com/sns/jscode2session",
		url.Values{"appid": {this.appid}, "secret": {this.appsecret}, "js_code": {code}, "grant_type": {"authorization_code"}})

	//time.Sleep(time.Duration(1000)*time.Millisecond)
	if err4 != nil {
		// handle error
		utils.Log.Warn("微信官方接口调用出现问题：", err4)
		//log.Printf("mistake:%v", err4)
		return nil, "微信官方接口调用出现问题!" + err4.Error()
	}

	defer resp.Body.Close()
	body, err5 := ioutil.ReadAll(resp.Body)
	if err5 != nil {
		// handle error
		utils.Log.Warn("微信官方接口调用后ReadAll函数出现问题：", err5)
		//log.Printf("mistake:%v", err5)
		return nil, "微信官方接口调用后ReadAll函数出现问题!" + err5.Error()
	}
	//fmt.Println(body)
	jsons := wrapper.NewSVObjectFromBufIfErrThenNew(body)

	//fmt.Println(jsons)
	session_key := jsons.StringByName("session_key", "")
	//allmsgJson, _ := wrapper.NewSVFromBuf([]byte(allneedmsg.allmsg))

	phonenumbermsgJson, _ := wrapper.NewSVFromBuf([]byte(phonenumbermsg))
	if phonenumbermsgJson == nil {
		return nil, "phonenumber json为空！"
	}
	detail := phonenumbermsgJson.ValueByName("detail")
	encryptedData := detail.StringByName("encryptedData", "")
	iv := detail.StringByName("iv", "")
	//str3 := encode(allneedmsg.encryptedData)

	//fmt.Println(phonenumbermsgJson)
	//fmt.Println(allneedmsg.encryptedData)
	//fmt.Println(str3)

	//userInfo := allmsgJson.StringByName("userInfo", "")

	nickName := ""
	avatarUrl := ""

	userInfoJson, _ := wrapper.NewSVFromBuf([]byte(userinfo))
	if userInfoJson == nil {
		//return nil,"userInfoJson json为空！"
		utils.Log.Warn("userInfoJson json为空！")
	} else {
		nickName = userInfoJson.StringByName("nickName", "")
		avatarUrl = userInfoJson.StringByName("avatarUrl", "")
	}

	//nickName,_ := wrapper.NewSVFromBuf([]byte(userInfo))
	//allneedmsg.session_key = jsons.StringByName("session_key","")
	//encryptedData = "CiyLU1Aw2KjvrjMdj8YKliAjtP4gsMZMQmRzooG2xrDcvSnxIMXFufNstNGTyaGS9uT5geRa0W4oTOb1WT7fJlAC+oNPdbB+3hVbJSRgv+4lGOETKUQz6OYStslQ142dNCuabNPGBzlooOmB231qMM85d2/fV6ChevvXvQP8Hkue1poOFtnEtpyxVLW1zAo6/1Xx1COxFvrc2d7UL/lmHInNlxuacJXwu0fjpXfz/YqYzBIBzD6WUfTIF9GRHpOn/Hz7saL8xz+W//FRAUid1OksQaQx4CMs8LOddcQhULW4ucetDf96JcR3g0gfRK4PC7E/r7Z6xNrXd2UIeorGj5Ef7b1pJAYB6Y5anaHqZ9J6nKEBvB4DnNLIVWSgARns/8wR2SiRS7MNACwTyrGvt9ts8p12PKFdlqYTopNHR1Vf7XjfhQlVsAJdNiKdYmYVoKlaRv85IfVunYzO0IKXsyl7JCUjCpoG20f0a04COwfneQAGGwd5oa+T8yO5hzuyDb/XcxxmK01EpqOyuxINew=="
	//iv := "r7BXXKkLb8qrSNn05n0qiA=="

	resdata := wrapper.NewSVObject().ForceByPath("data")
	if session_key == "" {
		fmt.Println("session_key为空")
		return nil, "session_key为空!"
	}
	pc := WxBizDataCrypt{AppId: this.appid, SessionKey: session_key}
	result, err3 := pc.Decrypt(encryptedData, iv, true) //第三个参数解释： 需要返回 JSON 数据类型时 使用 true, 需要返回 map 数据类型时 使用 false
	if err3 != nil {
		fmt.Println(err3)
		utils.Log.Warn("Decrypt函数出现问题：", err3)
		return nil, "Decrypt函数出现问题!"
	}
	//allneedmsg.phoneNumber = result
	result_str := fmt.Sprintf("%v", result)
	phonenumberJson, _ := wrapper.NewSVFromBuf([]byte(result_str))
	phoneNumber := phonenumberJson.StringByName("phoneNumber", "")

	if phoneNumber != "" {
		resdata.SetKeyValue("phoneNumber", phoneNumber)
		resdata.SetKeyValue("nickName", nickName)
		resdata.SetKeyValue("avatarUrl", avatarUrl)
		return resdata, ""
	} else {
		return nil, "未解析出手机号！"
	}

}
